package com.ai.bitcoin.jpa.service;

import com.ai.bitcoin.jpa.dao.BccBasicInfoDao;
import com.ai.bitcoin.jpa.entity.BccBasicInfo;
import lombok.Getter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Jason
 * @date 2018/2/4
 */
@Service
public class BccBasicInfoService {
    @Autowired
    @Getter
    private BccBasicInfoDao dao;

    @Transactional

    public BccBasicInfo save(BccBasicInfo bccBasicInfo) {
        return dao.save(bccBasicInfo);
    }

    public BccBasicInfo findByBccId(String bccId) {
        return dao.findByBccId(bccId);
    }

    @Cacheable(value = "BccBasicInfo_findByRecordState")
    public List<BccBasicInfo> findByRecordState(String bcState) {
        return dao.findByRecordState(bcState);
    }

    @CacheEvict(value = {
            "BccBasicInfo_findByBccId",
            "BccBasicInfo_findByRecordState",
            "BccBasicInfo_findByBccIdAndRecordState",
            "BccBasicInfo_findOneByRecordState",
            "getBccByKeyword"
    })
    public void update2Publish(String latestBatch) {
        dao.deleteOldPublish(latestBatch);
        dao.update2Publish(latestBatch);
    }

    @CacheEvict(value = {
            "BccBasicInfo_findByBccId",
            "BccBasicInfo_findByRecordState",
            "BccBasicInfo_findByBccIdAndRecordState",
            "BccBasicInfo_findOneByRecordState",
            "getBccByKeyword"
    })
    public void deleteNoPublish() {
        dao.deleteNoPublish();
    }

    @Cacheable(value = "BccBasicInfo_findByBccIdAndRecordState")
    public List<BccBasicInfo> findByBccIdAndRecordState(String bccId, String recordState) {
        return dao.findByBccIdAndRecordState(bccId, recordState);
    }

    @Cacheable(value = "BccBasicInfo_findOneByRecordState")
    public BccBasicInfo findOneByRecordState(String recordState) {
        return dao.findOneByRecordState(recordState);
    }

    /**
     * 根据关键词查询唯一BCC信息
     *
     * @param keyword 关键词
     * @return BCC信息
     */
    @Cacheable("getBccByKeyword")
    public BccBasicInfo getByKeyword(String keyword) {
        //bcc中英匹配
        List<BccBasicInfo> bccBasicInfoList = dao.findByKeyword(keyword);
        return CollectionUtils.isNotEmpty(bccBasicInfoList) ? bccBasicInfoList.get(0) : null;
    }

    /**
     * 订阅关键词
     *
     * @param message 收到的消息
     * @return 如果为关键词返回币信息 否则返回空
     */
    public BccBasicInfo subscribeKeywords(String message) {
        if (StringUtils.startsWith(message, "订阅")) {
            return getByKeyword(StringUtils.substring(message, 2));
        }
        return null;
    }
}
